<?php
namespace Admin\Controller;

use Common\Api\Wechat;
use Common\Controller\AuthController;
use Think\Exception;

/*
* 天晨订单模块
*/

class OrdersController extends AuthController
{

    protected $config;
    protected $open_id;//公众号openid
    protected $linkTtel;
    protected $wObj;

    public function _initialize()
    {

        parent::_initialize();
        $re = M('WechatConfig')->where("wid=%d", 1)->find();
       //获取配置数据
        $config = array(

            'appid' => $re['appid'], //填写高级调用功能的appid

            'appsecret' => $re['appsecret'], //填写高级调用功能的密钥

            'wechat_id' => $re['wid']//微信id
        );
        $this->linkTel=$re['aftertel'];
        $this->open_id = $re['open_id'];
        $this->config = $config;
        $this->wObj=new Wechat($this->config);


    }

    //进行中订单列表
    public function underwayOrderList()
    {
        $arr = D('Orders')->orderList(1);
        $this->assign('_list', $arr['list']);
        $this->assign('_page', $arr['page']->show());
        $this->assign('title', '订单列表-生产中');
        $this->display();
    }

    //已完成订单列表
    public function completedOrderList()
    {

        $arr = D('Orders')->orderList(2);
        $this->assign('_list', $arr['list']);
        $this->assign('_page', $arr['page']->show());
        $this->assign('title', '订单列表-已完成');
        $this->display();
    }

    //待审核订单列表
    public function stayOrderList()
    {
        $arr = D('Orders')->orderList(0);
        $this->assign('_list', $arr['list']);
        $this->assign('_page', $arr['page']->show());
        $this->assign('title', '订单列表-待审核');
        $this->display();

    }

    //制单
    public function makeForm()
    {
        $rid = $_GET['rid'];
        $result = D('Orders')->detail($rid);
        $plist=M('OrderProduct')->field("id,cate_name")->where("status=%d and pid=%d",[1,0])->select();
        $cre=M('Crafts')->field("id,pid,craft_name")->where("status=%d and pid=%d",[1,0])->select();
        $line=M('Linetypes')->field("id,pid,line_name")->where("status=%d and pid=%d",[1,0])->select();
        $lenth=M('LineLenth')->where("status=%d",1)->select();
        $colors=M('Color')->field("id,color_name,color_number")->where("status=%d",1)->select();
        $menxin=M('Goals')->where("status=%d",1)->select();
        $this->assign('menxin',$menxin);
        $this->assign('colors',$colors);
        $this->assign('lenth',$lenth);
        $this->assign('line',$line);
        $this->assign('cre',$cre);//工艺类型
        $this->assign('plist',$plist);
        $this->assign('result', $result);
        $this->assign('rid', $rid);
        $this->assign('title', '制作订单');
        $this->display();
    }

    //订单详情
    public function orderDetail()
    {
        $rid = $_GET['rid'];
        $result = D('Orders')->detail($rid);
        $this->assign('result', $result);
        $this->assign('title', '订单详情');
        $this->assign('rid', $rid);
        $this->display();
    }

    //提交制单
    public function putForm()
    {

        $rid = I('post.rid');
        if (D('Orders')->orderStatus($rid) !== 200) {
            $this->error('参数错误或无效的订单');
        } else {

            //获取商品数据
            $products = [];
            $products['productName'] = I('post.productName');
            $products['product_cate']=I('post.product_cate');
            $products['doorOpeningSize'] = I('post.doorOpeningSize');
            $products['doorLeafStandard'] = I('post.doorLeafStandard');
            $products['verticalPlate'] = I('post.verticalPlate');
            $products['cropupStandard'] = I('post.cropupStandard');
            $products['craftcate']=I('post.craftcate');
            $products['craft_name']=I('post.craft_name');
            $products['Numbers'] = I('post.Numbers');
            $products['linelength']=I('post.linelength');
            $products['line_cate']=I('post.line_cate');
            $products['linetype']=I('post.linetype');
            $products['wireNumber'] = I('post.wireNumber');
            $products['color'] = I('post.color');
            $products['discount']=I('post.discount');
            $products['price'] = I('post.price');
            $products['totalPrice']=I('post.totalPrice');
            $products['remark'] = I('post.remark');
            $products['goal_name']=I('post.goal_name');
            //得到商品数据
            $productArray = putarry($products, 'productName');

            $pcounts=count($productArray);

            //获取工艺信息
            $craft = [];
            $craft['processName'] = I('post.processName');
            $craft['labourCost'] = I('post.labourCost');
            $craft['constructionWorker'] = I('post.constructionWorker');
            $craft['requireTime'] = I('post.requireTime');
            $craft['completeTime'] = I('post.completeTime');
            //得到工艺数据
            $craftArray = putarry($craft, 'processName');

            //获取订单信息
            $dataOrder = [];
            $dataOrder['order_price'] = I('post.order_price');
            $dataOrder['downPayment'] = I('post.downPayment');
            $dataOrder['eecuPeople'] = $_SESSION['tc']['nickname'];
            $dataOrder['orderRemark'] = I('post.orderRemark');
            $dataOrder['sparemoney'] = I('post.sparemoney');
            $dataOrder['update_time'] = time();
            $dataOrder['status'] = 3;
            $dataOrder['admin_id'] = $_SESSION['tc']['uid'];
            $dataOrder['counts']=$pcounts;
            //获取原材料信息
            $material=[];
            $material['bracode']=I('post.bracode');
            $material['counts']=I('post.counts');
            $mateArray = putarry($material, 'bracode');

            $pObj = M('Products');
            $pObj->startTrans();//开启事务

            try {

                //写入商品数据
                foreach ($productArray as &$v) {
                    $v['totalPrice'] = $v['price'] * $v['Numbers'];
                    $v['rid'] = $rid;
                    $pObj->add($v);
                }

                //写入工序数据
                foreach ($craftArray as &$val) {
                    $val['rid'] = $rid;
                    M('Process')->add($val);
                }
                //更新订单
                $res = M('Orders')->where("rid=%d", $rid)->save($dataOrder);

                //写入原材料信息
                foreach($mateArray as &$value){
                    $value['rid']=$rid;
                    M('OrderMaterial')->add($value);
                    M('Finishedgood')->where("bracode='%s'",$value['bracode'])->setDec('counts',$value['counts']);
                }

                $pObj->commit();//提交事务
                if ($res) {
                    $url = 'http://' . $_SERVER['HTTP_HOST'] . '/Mobile/ClientServer/orderBaseDetail/stateid/100/rid/' . $rid;
                    $frist='您好！你的订单已创建成功,请确认您的订单信息';
                    $remark="如订单需要修改，请拨打我们的客服电话".$this->linkTel."。谢谢!";
                    $order_data=$this->order_msg($rid);
                    $open_id=$this->get_open_id($rid);
                    $templateData=[
                        'touser'=>$open_id,
                        'template_id'=>Wechat::TEMPLATE_SUCCESS,
                        'url' => $url,
                        'topcolor'=>Wechat::TEMPLATE_COLOR_THEME,
                        'data'=> [
                            'first'=>
                                ['value'=>$frist,'color'=>Wechat::TEMPLATE_COLOR_TEXT],
                            'orderno'=>
                                ['value'=>$order_data['order_number'],'color'=>Wechat::TEMPLATE_COLOR_TEXT],
                            'refundno'=>
                                ['value'=>$pcounts,'color'=>Wechat::TEMPLATE_COLOR_TEXT],
                            'refundproduct'=>
                                ['value'=>$order_data['order_price'],'color'=>Wechat::TEMPLATE_COLOR_TEXT],
                            'remark'=>['value'=>$remark,'color'=>Wechat::TEMPLATE_COLOR_TEXT]
                        ],
                    ];

                     $this->wObj->sendTemplateMessage($templateData);

                }
                $this->success('提交成功', U('Orders/toBeConfirmed'));

            } catch (Exception $e) {

                $pObj->rollback();//事务回滚
                $this->error('提交失败');
            }
        }
    }

    public function cesi($rid='')
    {
        $this->sendTemplateMsg($rid);
    }


    protected function get_open_id($rid)
    {
        $user_id = M('Orders')->where("rid=%d", $rid)->getField('user_id');
        $touser = M('DealerUserinfo')->where("id=%d", $user_id)->getField('open_id');//用户微信id
        return $touser;
    }


    //打印页面
    public function printInfo()
    {

        $rid = $_GET['rid'];
        $re = D('Orders')->detail($rid);
        $garr = M('Process')->where("rid=%d", $rid)->select();
        $parr = M('Products')->where("rid=%d", $rid)->select();
        $bankarr = M('WechatConfig')->find();
        $this->assign('garr', $garr);
        $this->assign('parr', $parr);
        $this->assign('re', $re);
        $this->assign('bankarr', $bankarr);
        $this->assign('title', '打印订单');
        $this->display();
    }

    //生产中订单详情
    public function underwayOrderDetail()
    {
        $rid = $_GET['rid'];
        $re = D('Orders')->detail($rid);
        $garr = M('Process')->where("rid=%d", $rid)->select();
        $parr = M('Products')->where("rid=%d", $rid)->select();
        $bankarr = M('WechatConfig')->find();
        $this->assign('garr', $garr);
        $this->assign('parr', $parr);
        $this->assign('re', $re);
        $this->assign('bankarr', $bankarr);
        $this->assign('title', '生产中-订单详情');
        $this->display();
    }

    /**查询订单信息
     * @param $rid
     * @return mixed
     */
    protected function order_msg($rid)
    {
       return M('Orders')->where("rid=%d",$rid)->find();
    }


    // 更新订单状态
    public function changeOrder($pr_id=null)
    {
        if (IS_POST) {
            $rid = $_POST['rid'];
            $rdata = M('Orders')->where("rid=%d", $rid)->find();
            if ($rdata['status'] != 1) {
                $this->error('只能操作生产中的订单!');
                exit;
            }

            $_POST['admin_id'] = $_SESSION['tc']['uid'];
            $_POST['t_time'] = time();
            $arr = D('Tailafter')->orderState('', $_POST);
            if ($arr['state'] == 'success') {
                M('Process')->where("pr_id=%d",$pr_id)->save(['completeTime'=>date('Y-m-d H:i:s',time())]);//写入工序完成时间
                $url = 'http://' . $_SERVER['HTTP_HOST'] . '/Mobile/ClientServer/orderDetail/rid/' . $rid;
                $order_data=$this->order_msg($rid);
                $open_id=$this->get_open_id($rid);
                $templateData=[
                    'touser'=>$open_id,
                    'template_id'=>Wechat::TEMPLATE_AFTER,
                    'url' => $url,
                    'topcolor'=>Wechat::TEMPLATE_COLOR_THEME,
                    'data'=> [
                        'first'=>
                            ['value'=>$_POST['title'],'color'=>Wechat::TEMPLATE_COLOR_TEXT],
                        'keyword1'=>
                            ['value'=>$order_data['order_number'],'color'=>Wechat::TEMPLATE_COLOR_TEXT],
                        'keyword2'=>
                            ['value'=>'生产中','color'=>Wechat::TEMPLATE_COLOR_TEXT],
                        'keyword3'=>
                            ['value'=>'定制商品','color'=>Wechat::TEMPLATE_COLOR_TEXT],
                        'remark'=>['value'=>$_POST['content'],'color'=>Wechat::TEMPLATE_COLOR_TEXT]
                    ],
                ];

                $this->wObj->sendTemplateMessage($templateData);

                $this->success($arr['info']);
            } else {
                $this->error($arr['info']);
            }

        } else {
            $rid = $_GET['rid'];
            $list = D('Tailafter')->stateList($rid);
            $parr=M('process')->field("pr_id,processName")->where("rid=%d",$rid)->select();
            $data = M('orders')->field("order_number,company_name,area_name,username,mobile_phone,status")->where("rid=%d", $rid)->find();
            $this->assign('data', $data);
            $this->assign('_list', $list);
            $this->assign('rid', $rid);
            $this->assign('parr',$parr);
            $this->assign('title', '更新订单信息');
            $this->display();
        }

    }

    //编辑订单状态
    public function editOrder($pr_id=null)
    {
        $rid = $_POST['rid'];
        $rdata = M('Orders')->where("rid=%d", $rid)->find();
        if ($rdata['status'] != 1) {
            $this->error('只能操作生产中的订单!', '', IS_AJAX);
            exit;
        }
        $tid = $_POST['tid'];
        $_POST['t_time'] = time();
        $arr = D('Tailafter')->orderState($tid, $_POST);
        if ($arr['state'] == 'success') {
            M('Process')->where("pr_id=%d",$pr_id)->save(['completeTime'=>date('Y-m-d H:i:s',time())]);//写入工序完成时间
            $url = 'http://' . $_SERVER['HTTP_HOST'] . '/Mobile/ClientServer/orderDetail/stateid/100/rid' . $rid;
            $content = "【您的订单有新状态】订单信息根据您再次确认已作更改，点击查看详情,如有任何疑问，请拨打我们的客服电话".$this->linkTel."。谢谢!";
            $order_data=$this->order_msg($rid);
            $open_id=$this->get_open_id($rid);
            $templateData=[
                'touser'=>$open_id,
                'template_id'=>Wechat::TEMPLATE_AFTER,
                'url' => $url,
                'topcolor'=>Wechat::TEMPLATE_COLOR_THEME,
                'data'=> [
                    'first'=>
                        ['value'=>$_POST['title'],'color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'keyword1'=>
                        ['value'=>$order_data['order_number'],'color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'keyword2'=>
                        ['value'=>'生产中','color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'keyword3'=>
                        ['value'=>'定制商品','color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'remark'=>['value'=>$content,'color'=>Wechat::TEMPLATE_COLOR_TEXT]
                ],
            ];
            $this->wObj->sendTemplateMessage($templateData);
            $this->success($arr['info']);
        } else {
            $this->error($arr['info']);
        }
    }

    //删除订单
    public function rdelete($tid = '', $rid = '')
    {

        $rdata = M('Orders')->where("rid=%d", $rid)->find();
        if ($rdata['status'] != 1) {
            $this->error('只能操作生产中的订单!', '', IS_AJAX);
            exit;
        }
        $result = M('Tailafter')->where("tid=%d", $tid)->delete();
        if ($result) {
            $this->success('删除成功', '', IS_AJAX);
        } else {
            $this->error('删除失败', '', IS_AJAX);
        }

    }

    //完成订单
    public function completeOrder($rid = '')
    {

        $re = M('Orders')->where("rid=%d", $rid)->save(['status' => 2]);
        if ($re) {
            $url = 'http://' . $_SERVER['HTTP_HOST'] . '/Mobile/ClientServer/orderDetail/rid/' . $rid;
            $content = "你的订单已完成,点击查看详情,如有任何疑问，请拨打我们的客服电话".$this->linkTel."。谢谢!";
            $order_data=$this->order_msg($rid);
            $open_id=$this->get_open_id($rid);
            $templateData=[
                'touser'=>$open_id,
                'template_id'=>Wechat::TEMPLATE_COMPLETE,
                'url' => $url,
                'topcolor'=>Wechat::TEMPLATE_COLOR_THEME,
                'data'=> [
                    'first'=>
                        ['value'=>'你的订单中的商品已经生产完成','color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'keyword1'=>
                        ['value'=>date('Y-m-d H:i:',time()),'color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'keyword2'=>
                        ['value'=>$order_data['order_number'],'color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'keyword3'=>
                        ['value'=>'定制商品','color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'keyword4'=>
                        ['value'=>'已全部生产','color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'keyword5'=>
                        ['value'=>'已完成','color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'remark'=>['value'=>$content,'color'=>Wechat::TEMPLATE_COLOR_TEXT]
                ],
            ];

            $this->wObj->sendTemplateMessage($templateData);

            $this->success('提交成功', '', IS_AJAX);
        } else {
            $this->error('提交失败', '', IS_AJAX);
        }

    }

    //发送客服消息
    protected function sendMessage($rid, $content)
    {
        $user_id = M('Orders')->where("rid=%d", $rid)->getField('user_id');
        $touser = M('DealerUserinfo')->where("id=%d", $user_id)->getField('open_id');//用户微信id
        if ($touser) {
            $wobj = new Wechat($this->config);
            $data = [];
            $data['touser'] = $touser;
            $data['msgtype'] = 'text';
            $data['text'] = ['content' => $content];
            $send = $wobj->sendCustomMessage($data);
            if ($send !== false) {
                return true;
            } else {
                return false;
            }

        }
    }



    //待确认订单
    public function toBeConfirmed()
    {
        $arr = D('Orders')->orderList(3);
        $this->assign('_list', $arr['list']);
        $this->assign('_page', $arr['page']);
        $this->assign('title', '订单列表-待确认');
        $this->display();
    }

    //修改订单
    public function orderUpdate()
    {
        if(IS_POST){
            $_POST['cid']=0;
            if(M('Orders')->where("rid=%d",$_POST['rid'])->save($_POST)){
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            }
        }else{
            $rid=$_GET['rid'];
            $arr=M('Orders')->where("rid=%d",$rid)->find();
            $this->assign('arr',$arr);
            $this->assign('title','修改订单');
            $this->display();
        }


    }
    //修改产品信息
    public function updateProduct($rid='')
    {

        if(IS_POST){
            $productArray = putarry($_POST, 'product_cate');
             $pobj=M('Products');
             $pobj->startTrans();//开启事务
            try{
                foreach ($productArray as &$v) {
                    if(isset($v['id']) && !empty($v['id']) ){
                        $pobj->where("id=%d",$v['id'])->save($v);
                    }else{
                        $v['rid']=$rid;
                        $pobj->add($v);
                    }

                }
                $pobj->commit();
                $this->success('修改成功');
            }catch(Exception $e){
                $pobj->rollback();
                $this->error('修改失败');
            }

        }else{
            $list=M('Products')->where("rid=%d",$rid)->select();
            $plist=M('OrderProduct')->field("id,cate_name")->where("status=%d and pid=%d",[1,0])->select();
            $cre=M('Crafts')->field("id,pid,craft_name")->where("status=%d and pid=%d",[1,0])->select();
            $line=M('Linetypes')->field("id,pid,line_name")->where("status=%d and pid=%d",[1,0])->select();
            $lenth=M('LineLenth')->where("status=%d",1)->select();
            $colors=M('Color')->field("id,color_name,color_number")->where("status=%d",1)->select();
            $this->assign('colors',$colors);
            $this->assign('lenth',$lenth);
            $this->assign('line',$line);
            $this->assign('cre',$cre);//工艺类型
            $this->assign('plist',$plist);
            foreach($list as &$v){
                $product_cate=$v['product_cate'];//商品分类id
                $craftcate=$v['craftcate'];//工艺分类id
                $line_cate=$v['line_cate'];//型号分类id
                $v['orderproduct']= M('OrderProduct')->field("id,cate_name")->where("pid=%d and status=%d",[$product_cate,1])->select();
                $v['crafts']=M('Crafts')->field("id,craft_name")->where("pid=%d and status=%d",[$craftcate,1])->select();
                $v['linetypes']=M('Linetypes')->field('id,line_name')->where("pid=%d and status=%d",[$line_cate,1])->select();
            }
            $this->assign('_list',$list);
            $this->assign('rid',$rid);
            $this->assign('title','修改产品信息');
            $this->display();
        }

    }
    //删除商品信息
    public function pdel($id='')
    {
        if(IS_AJAX){
            if(M('Products')->where("id=%d",$id)->delete()){
                $this->success('删除成功','',IS_AJAX);
            }else{
                $this->error('删除失败','',IS_AJAX);
            }
        }


    }


    //修改工艺信息
    public function updateCraft($rid='')
    {

        if(IS_POST){
            $craftArray = putarry($_POST, 'processName');
            $obj=M('process');
            $obj->startTrans();//开启事务
            try{
                foreach($craftArray as $v){
                    if(isset($v['pr_id']) && !empty($v['pr_id']) ){
                        $obj->where("pr_id=%d",$v['pr_id'])->save($v);
                    }else{
                        $v['rid']=$rid;
                        $obj->add($v);
                    }
                }
                $obj->commit();
                $this->success('修改成功');

            }catch (Exception $e){
                $obj->rollback();
                $this->error('修改失败');
            }


        }else{
            $list=M('Process')->where("rid=%d",$rid)->select();
            $this->assign('_list',$list);
            $this->assign('rid',$rid);
            $this->assign('title','修改工艺信息');
            $this->display();
        }

    }
    //删除工艺信息
    public function gongyidel($pr_id='')
    {
        if(IS_AJAX){
            if(M('Process')->where("pr_id=%d",$pr_id)->delete()){
                $this->success('删除成功','',IS_AJAX);
            }else{
                $this->error('删除失败','',IS_AJAX);
            }
        }
    }
    //开始生产
    public function startProduction($rid='')
    {
        $info=M('Orders')->where("rid=%d",$rid)->find();
        if($info['is_audit']==0){
            $this->error('订单审核后才能生产','',IS_AJAX);
            exit;
        }
        if($info['is_finance']==0){
            $this->error('财务审核后才能生产','',IS_AJAX);
            exit;
        }

        if(M('Orders')->where("rid=%d",$rid)->save(['status'=>1])){
            $url = 'http://' . $_SERVER['HTTP_HOST'] . '/Mobile/ClientServer/orderDetail/rid/' . $rid;
            $remark = "恭喜您，你的订单已经通过审核，马上开始生产，请耐心等待！点击查看详情，如有任何疑问，请拨打我们的客服电话".$this->linkTel."。谢谢!";
            $order_data=$this->order_msg($rid);
            $open_id=$this->get_open_id($rid);
            $templateData=[
                'touser'=>$open_id,
                'template_id'=>Wechat::TEMPLATE_ORDER_PASS,
                'url' => $url,
                'topcolor'=>Wechat::TEMPLATE_COLOR_THEME,
                'data'=> [
                    'first'=>
                        ['value'=>'你的订单已经通过审核','color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'keyword1'=>
                        ['value'=>$order_data['order_number'],'color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'keyword2'=>
                        ['value'=>'通过','color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'keyword3'=>
                        ['value'=>'系统管理员','color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'keyword4'=>
                        ['value'=>date('Y-m-d H:i:s',time()),'color'=>Wechat::TEMPLATE_COLOR_TEXT],
                    'remark'=>
                        ['value'=>$remark,'color'=>Wechat::TEMPLATE_COLOR_TEXT]
                ],
            ];

            $this->wObj->sendTemplateMessage($templateData);

            $this->success('操作成功',U('Orders/underwayOrderList'),IS_AJAX);
        }else{
            $this->error('操作失败','',IS_AJAX);
        }

    }
    //修改原材料信息
    public function updateMaterial($rid='')
    {

        if(IS_POST){
            $area_id=$_SESSION['tc']['area_id'];
            $mArray = putarry($_POST, 'om_id');
            $obj=M('OrderMaterial');
            $obj->startTrans();//开启事务
            try{
                foreach($mArray as $v){
                    if(isset($v['om_id']) && !empty($v['om_id']) ){
                        $cts=$obj->where("om_id=%d",$v['om_id'])->getField('counts');
                        $newCount=$v['counts']-$cts;
                        $obj->where("om_id=%d",$v['om_id'])->save($v);
                        M('Finishedgood')->where("bracode='%s' and area_id=%d",[$v['bracode'],$area_id])->setDec('counts',$newCount);
                    }else{
                        $v['rid']=$rid;
                        $obj->add($v);
                        M('Finishedgood')->where("bracode='%s' and area_id=%d",[$v['bracode'],$area_id])->setDec('counts',$v['counts']);
                    }
                }
                $obj->commit();
                $this->success('修改成功');

            }catch (Exception $e){
                $obj->rollback();
                $this->error('修改失败');
            }

        }else{
            $list=M('OrderMaterial')->alias("a")
                ->field("a.*,b.m_name,b.standard,b.sell_price,b.m_number")
                ->join("sr_material as b on a.bracode=b.bracode")
                ->where("a.rid=%d and a.status=%d",[$rid,1])->select();

            $this->assign('_list',$list);
            $this->assign('rid',$_GET['rid']);
            $this->assign('title','修改原材料');
            $this->display();
        }


    }
    //删除原材料
    public function mdels($om_id='')
    {
        $area_id=$_SESSION['tc']['area_id'];
        $mobj=M('OrderMaterial');
        try{
            $re=$mobj->where("om_id=%d",$om_id)->find();
            M('Finishedgood')->where("bracode='%s' and area_id=%d",[$re['bracode'],$area_id])->setInc('counts',$re['counts']);
            $mobj->where("om_id=%d",$om_id)->delete();
            $mobj->commit();
            $this->success('删除成功','',IS_AJAX);
        }catch (Exception $e){
            $mobj->rollback();
            $this->error('删除失败','',IS_AJAX);
        }

    }
    //修改工序
    public function updatework($rid=null,$pr_id=null,$content=null){

        if(IS_POST){
           $data['rid']=$rid;
           $data['pr_id']=$pr_id;
           $data['content']=$content;
           $data['create_at']=time();
           $data['admin_id']=$_SESSION['tc']['uid'];
           $data['constructionWorker']= M('Process')->where("pr_id=%d",$pr_id)->getField('constructionWorker');
           unset($_POST['rid']);
           unset($_POST['pr_id']);
           unset($_POST['content']);
           $result=putarry($_POST);//原材料信息
            $model=M('Upwork');
            $model->startTrans();
            try{
                $fid=$model->add($data);
                foreach ($result as $v){
                    $v['fid']=$fid;
                    M('Workmaterial')->add($v);
                    M('Finishedgood')->where("bracode='%s'",$v['bracode'])->setDec('counts',$v['counts']);
                }
                $model->commit();
                $this->success('提交成功');
            }catch (Exception $e){
                $model->rollback();
                $this->error('提交失败');
            }
        }else{
            $rid = $_GET['rid'];
            $list=M('Upwork')->alias("a")->field("a.*,b.processName")->join("sr_process as b ON a.pr_id=b.pr_id")->where("a.rid=%d and a.status=%d",[$rid,1])->select();
            $parr=M('process')->field("pr_id,processName")->where("rid=%d",$rid)->select();
            $data = M('orders')->field("order_number,company_name,area_name,username,mobile_phone,status")->where("rid=%d", $rid)->find();
            $this->assign('data', $data);
            $this->assign('rid', $rid);
            $this->assign('parr',$parr);
            $this->assign('_list',$list);
            $this->assign('title', '修改工序');
            $this->display();
        }

    }
    //删除返工信息
    public function cancel($fid=null){
        $model=M('Upwork');
        $model->startTrans();
        try{
            $model->where("fid=%d",$fid)->save(['status'=>-1]);
            $data=M('Workmaterial')->field("bracode,counts")->where("fid=%d status=%d",[$fid,1])->select();
            foreach ($data as $v){
                M('Finishedgood')->where("bracode='%s'",$v['bracode'])->setInc('counts',$v['counts']);
            }
            M('Workmaterial')->where("fid=%d",$fid)->save(['status'=>-1]);
            $model->commit();
            $this->success('取消成功');
        }catch (Exception $e){
            $model->rollback();
            $this->error('取消失败');
        }

    }


}









